<template>
  <div ref="container"></div>
</template>
<script setup lang="ts">
import {
  ref,
  inject,
  onMounted,
  onBeforeUnmount,
  onUpdated,
  markRaw,
} from "vue";
import type { ECharts, EChartsOption } from "echarts";
// 获取echart挂载的DOM节点
const container = ref();
const myChart = ref<ECharts>();

// 通过 inject 接收Echarts
const Echarts: ECharts = inject("$echarts");

const initEchartsOneFn = () => {
  // echarts初始化
  myChart.value = markRaw((Echarts as any).init(container.value));

  // let myChart = proxy.$echarts.init(container.value);

  const option: EChartsOption = {
    // 自定义echarts图标相关配置
    title: {
      text: "ECharts 入门示例",
    },
    tooltip: { trigger: "axis" },
    legend: {
      data: ["销量"],
    },
    series: [
      {
        name: "销量",
        type: "pie",
        radius: "55%",
        center: ["50%", "60%"],
        data: [
          { value: 335, name: "直接访问" },
          { value: 310, name: "邮件营销" },
          { value: 234, name: "联盟广告" },
          { value: 135, name: "视频广告" },
          { value: 1548, name: "搜索引擎" },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  myChart.value.setOption(option);
  // 根据页面大小自动响应图表大小
  window.addEventListener("resize", function () {
    if (myChart.value) {
      myChart.value?.resize();
    }
  });
};
onUpdated(() => {
  if (myChart.value) {
    myChart.value?.resize();
  }
});
onMounted(() => {
  initEchartsOneFn();
});
onUpdated(() => {
  myChart.value.resize();
});

onBeforeUnmount(() => {
  // 销毁echarts实例
  myChart.value = (Echarts as any).getInstanceByDom(container.value);
  myChart.value.dispose();
});
</script>
